package com.xz;

import org.junit.Test;

import java.util.Stack;

/**
 * @author XZ
 * @create 2021-04-23 20:35
 * https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
 */
public class _150_逆波兰表达式求值 {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        Integer result;
        for (String token : tokens) {
            if (isOperation(token)) {//为运算符
                Integer right = stack.pop();
                Integer left = stack.pop();
                if (token == "+") {
                    result = right + left;
                } else if (token == "-") {
                    result = left - right;
                } else if (token == "*") {
                    result = left * right;
                } else {
                    result = left / right;
                }
                stack.push(result);
            } else {//不是运算符
                stack.push(Integer.parseInt(token));
            }
        }
        return stack.pop();
    }

    private boolean isOperation(String token) {
        return token == "+" || token == "-" || token == "*" || token == "/";
    }

    @Test
    public void test01() {
        String[] tokens1 = {"2", "1", "+", "3", "*"};//9
        System.out.println(evalRPN(tokens1));

        String[] tokens2 = {"4", "13", "5", "/", "+"};//6
        int i = evalRPN(tokens2);
        System.out.println(i);

        String[] tokens3 = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
        int i2 = evalRPN(tokens3);
        System.out.println(i2);

        String[] tokens4 = {"2", "1", "+", "3", "*"};
        int i1 = evalRPN(tokens4);
        System.out.println(i1);
    }
}
